<?php
/**
 * 抽奖管理
 */
namespace Admin\Controller;
use Think\Controller;

class LotteryController extends CommonController
{
    protected $model;
    protected $return;
    protected $userId = 1;
    protected function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
        parent::_initialize();
    
        $sess_auth = session('user_auth');
        if (!$sess_auth) {
            $this->ajaxReturn(array('errcode'=>10000,'errmsg'=>'请先登录','url'=>U('/Public/login')),'JSON');
        }
         // 获取当前用户ID
        $uid = is_login();
        if(!$uid){// 还没登录 跳转到登录页面
           $this->ajaxReturn(array('errcode'=>10000,'errmsg'=>'请先登录','url'=>U('/Public/login')),'JSON');
        }
        $this->userId = $uid;
        $this->model = D('Lottery');
        $this->return = array('errcode'=>0, 'errmsg'=>'ok');

    }

    //列表
    public function index($type = 0)
    {
        if (IS_POST) {
            $data['name']   = I('post.name', '', 'trim');//名称
            $data['id']     = I('post.id', 0, 'intval');//ID
            $data['status'] = I('post.status', -1, 'intval');//状态0下线1上线
            $data['start']  = I('post.start', '', 'trim');//开始区间
            $data['end']    = I('post.end', '', 'trim'); //结束区间。
            $data['type']   = I('post.type', 0, 'intval'); //类型1业主2师傅
            $data['admin_user'] = I('post.admin_user', '', 'trim'); //创建人
            $pageIndex = I('post.page', 1, 'intval');

            $res = $this->model->getList($data, $pageIndex);
            if ($res !== false) {
                $res = array_merge($res, $this->return);
            }else{
                $res = $this->model->getError();
            }
            $this->ajaxReturn($res, 'JSON');
        }else{
            $this->assign('breadcrumb1', '签到抽奖');
            if($type == 1){
                $this->assign('breadcrumb2', '业主端');
            }else{
                $this->assign('breadcrumb2', '师傅端');
            }
            $this->assign('breadcrumb3', '活动管理');
           
            $this->assign('type', $type);
            $this->assign('url3', U('Lottery/index', array('type'=>$type)));
            $this->assign('new_url', U('Lottery/add', array('type'=>$type)));


            $this->display();
        }
    }

    public function test()
    {
        $this->display();
    }

    //新增
    public function add()
    {
        if(IS_GET){
            $type = I('get.type', 1);
            $id = I('get.id', '');
            $this->assign('breadcrumb1', '签到抽奖');
            if($type == 1){
                $this->assign('breadcrumb2', '业主端');
            }else{
                $this->assign('breadcrumb2', '师傅端');
            }
            $this->assign('breadcrumb3', '活动管理');
            if($id > 0){
                $this->assign('breadcrumb4', '编辑活动');
            }else{
                $this->assign('breadcrumb4', '新增活动');
            }
            $this->assign('type', $type);
            $this->assign('id', $id);
            $this->assign('url3', U('Lottery/index', array('type'=>$type)));
            $this->assign('url4', U('Lottery/add', array('type'=>$type)));

            $this->display();
            exit;
        }
        $data = $this->model->create($_POST, 1);
        if (!$data) {
            $ret['errcode'] = 10001;
            $ret['errmsg'] = $this->model->getError();
            $this->ajaxReturn($ret, 'JSON');
        }
        //检验转盘数据 
        $prize = $this->model->checkPrize($data['type']);
        if (!$prize) {
            $this->ajaxReturn($this->model->getErrMsg(),'JSON');
        }

        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time'].' 23:59:59');
        $data['add_time'] = time();
        $data['status'] = 0;  //初始状态未上线
        $data['admin_id'] = $this->userId;
        //计算每日场次
        if ($data['type'] == 1) { //业主每日一场签到
            $data['times'] = 1;
        }else{
            $data['times'] = ceil(($data['end_hour'] - $data['start_hour']) / $data['period']);
        }

        $data['per_amount'] = $prize['amount'];
        $days = ceil(($data['end_time'] - $data['start_time']) / 86400);
        $data['amount'] = $data['times'] * $data['per_amount'] * $days;

        //开启事务
        $this->model->startTrans(); 
        //插入活动记录
        $res = $this->model->add($data);
        if($res){
            //插入关联奖品列表
            $prize = $prize['prize'];
            foreach($prize as $k => $v){
                $prize[$k]['lottery_id'] = $res;
                $prize[$k]['admin_id'] = $this->userId;
            }
            $insertRes = M('LotteryPrize')->addAll($prize);
            //$insertRes = $this->model->addPrize($res, $data['type']);
            if ($insertRes) {
                //奖品插入成功，提交事务
                $this->model->commit();
                //操作日志
                $this->model->operatelog($this->userId, $this->userName, '签到活动', 1, $res);
                $this->ajaxReturn($this->return, 'JSON');
            }else{
                //否则，回滚
                $this->model->rollback();
                $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'操作失败'), 'JSON');
            }
        }else{
            $this->model->rollback();
            $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'操作失败'), 'JSON');
        }
        
    }
    //编辑
    public function edit()
    {
        if (IS_POST) {
            $id = I('post.id', 0, 'intval');
            $lottery = $this->model->getLotteryById($id);
            if (!$lottery) {
                $this->ajaxReturn($this->model->getErrMsg(),'JSON');    
            }else{
                $this->return['data'] = $lottery;
                $this->ajaxReturn($this->return,'JSON');
            }  
        }else{
            $this->display();
        }
    }
    //更新数据
    public function update()
    {
        $data = $this->model->field('id,name,end_time,remark')->create($_POST, 2);
        if (!$data) {
            $ret['errcode'] = 10001;
            $ret['errmsg'] = $this->model->getError();
            $this->ajaxReturn($ret, 'JSON');
        }
        $lottery = $this->model->find($data['id']);
        if (!$lottery) {
            $this->ajaxReturn(array('errcode'=>20001,'errmsg'=>'要更新的活动不存在'), 'JSON');
        }
        if (isset($data['end_time'])) {
            $data['end_time'] = strtotime($data['end_time'].' 23:59:59');
            if($data['end_time'] < $lottery['start_time']){
                $this->ajaxReturn(array('errcode'=>10001,'errmsg'=>'结束时间不能小于开始时间'),'JSON');
            }
            //如果修改了结束时间，重新计算奖池金额
            $days = ceil(($data['end_time'] - $lottery['start_time']) / 86400);
            $data['amount'] = $lottery['times'] * $lottery['per_amount'] * $days;
        }
        $data['update_time'] = time();

        $res = $this->model->save($data);
        if($res !== false){
            //更新缓存
            $this->model->clearCache($data['id']);
            //操作日志
            $this->model->operatelog($this->userId, $this->userName, '签到活动', 3, $data['id']);
            $this->ajaxReturn($this->return, 'JSON');
        }else{
            $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'更新失败'), 'JSON');
        }
       
    }

    //删除用户中奖记录
    public function del()
    {
        $map['user_id'] = I('post.user_id', 0, 'intval');
        $map['role'] = I('role', 0, 'intval');
        $map['is_deleted'] = 0;
        $data['is_deleted'] = 1;
        $res = M('LotteryRecord')->where($map)->save($data);
        if ($res) {
            $this->ajaxReturn(array('errcode'=>0,'errmsg'=>'ok'), 'JSON');
        }else{
            $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'操作失败'),'JSON');
        }
    }

    //上下线
    public function changestatus()
    {
        $data['id'] = I('post.id', 0, 'intval');
        $data['status'] = I('post.status');
        if (!in_array($data['status'], array(0,1))) {
            $this->ajaxReturn(array('errcode'=>10001,'errmsg'=>'状态错误'), 'JSON');
        }
        //如果上线，确认同一时间只允许一个活动上线
        if (!$lottery = $this->model->canChangeStatus($data['id'], $data['status'])) {
            $this->ajaxReturn($this->model->getErrMsg(), 'JSON');
        }
        $data['update_time'] = time();
        if ($data['status'] == 1) {
            $map['type'] = $lottery['type'];
            $this->model->where($map)->save(array('status'=>0));
        }
        $res = $this->model->save($data);
        if($res !== false){
            $this->model->clearCache($data['id']);
            $this->model->operatelog($this->userId, $this->userName, '签到活动', 3, $data['id']);
            $this->ajaxReturn($this->return, 'JSON');
        }else{
            $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'更新失败'), 'JSON');
        }

    }
    
    //获取电子券
    public function coupon()
    {
        $pageIndex = I('post.page', 1, 'intval');
        $pageSize = I('post.page_size', 10, 'intval');
        $pageIndex <= 0 and $pageIndex = 1;
        $pageSize <= 0 and $pageSize = 10;

        $volumeName = I('post.volume_name', '', 'trim');
        $volumeNum = I('post.volume_num', '', 'trim');
        $id = I('post.volume_id', 0, 'intval');
        $map['status'] = 1; //只显示生效的电子券
        if ($id) {
            $map['volume_id'] = $id;
        }else{
            $map['is_deleted'] = 0;
            $map['end_time'] = array('gt', time());
        }
        if ($volumeNum) {
            $map['volume_number'] = array('like', '%'.$volumeNum.'%');
        }
        if ($volumeName) {
            $map['volume_name'] = array('like', '%'.$volumeName.'%');
        }
        $total = M('Volume')->where($map)->count();
        $page = pagination($total, $pageSize ,$pageIndex);
        if ($total > 0) {
            $data = M('Volume')->where($map)->order('end_time desc')
                  ->limit($page['offset'], $page['limit'])->select();
            foreach ($data as $k => $v) {
                $data[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                $data[$k]['start_time'] = date('Y-m-d', $v['start_time']);
                $data[$k]['end_time'] = date('Y-m-d', $v['end_time']);
                $data[$k]['type'] = $v['type'] == 1 ? '代金券' : '现金券';
            }
        }else{
            $data = array();
        }
        $this->return['data'] = $data;
        $this->return['page'] = $page;
        $this->ajaxReturn($this->return);            
    }
    /**
     * 查看日志
     * @return [type] [description]
     */
    public function log()
    {
        if (IS_POST) {
            $data['start'] = I('post.start', '', 'trim');
            $data['end']   = I('post.end', '', 'trim');
            $data['rec_id'] = I('post.rec_id', '', 'trim');
            $data['lottery_id'] = I('post.lottery_id', '', 'trim');
            $data['user_id'] = I('post.user_id', '', 'trim');
            $data['user_name'] = I('post.user_name', '', 'trim');
            $data['type'] = I('post.type', 0, 'intval');
            $data['name'] = I('post.name', '', 'trim');
            $data['page'] = I('post.page', 1, 'intval');
            $data['page_size'] = I('post.page_size', 10, 'intval');

            $res = $this->model->getLogList($data);
            if($res !== false){
                $this->return['data'] = $res['data'];
                $this->return['page'] = $res['page'];
                $this->ajaxReturn($this->return, 'JSON');
            }else{
                $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'查找失败'), 'JSON');
            }
        }else{
            $isIFrame = I('get.isIFrame', 0);
            $type = I('get.type', 1);
            if($isIFrame){
                $id = I('get.id','');
                $name = I('get.name', '');
                $term = I('get.term', '');
                $this->assign('type', $type);
                $this->assign('id', $id);
                $this->assign('isIFrame', $isIFrame);
                $this->assign('name', urldecode($name));
                $this->assign('term', $term);
                $this->display('log_iframe');
                exit;
            }
            
            $this->assign('breadcrumb1', '签到抽奖');
            if($type == 1){
                $this->assign('breadcrumb2', '业主端');
            }else{
                $this->assign('breadcrumb2', '师傅端');
            }
            $this->assign('breadcrumb3', '查看日志');
            $this->assign('type', $type);
            $this->assign('url3', U('Lottery/log', array('type'=>$type)));
            $this->display();
        }
    }

    //统计
    public function stastics()
    {
        if (IS_POST) {
            $data['start'] = I('post.start', '', 'trim');
            $data['end']   = I('post.end', '', 'trim');
            $data['lottery_id'] = I('post.lottery_id', 0, 'intval');
            $data['name'] = I('post.name', '', 'trim');
            $data['page'] = I('post.page', 1, 'intval');
            $data['page_size'] = I('post.page_size', 10, 'intval');
            $data['group'] = I('post.group', 0, 'intval');
            $data['type'] = I('post.type', 0, 'intval');
            $res = $this->model->getStastics($data);
            if($res !== false){
                $this->return['data'] = $res['data'];
                $this->return['page'] = $res['page'];
                $this->ajaxReturn($this->return, 'JSON');
            }else{
                $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'查找失败'), 'JSON');
            }
        }else{
            $type = I('get.type', 1);
            $this->assign('breadcrumb1', '签到抽奖');
            if($type == 1){
                $this->assign('breadcrumb2', '业主端');
            }else{
                $this->assign('breadcrumb2', '师傅端');
            }
            $this->assign('breadcrumb3', '统计分析');
           
            $this->assign('type', $type);
            $this->assign('url3', U('Lottery/stastics', array('type'=>$type)));
            $this->display('analyze');
        }
    }

    //导出
    public function download()
    {
        $data['start'] = I('post.start', '', 'trim');
        $data['end']   = I('post.end', '', 'trim');
        $data['rec_id'] = I('post.rec_id', '', 'trim');
        $data['lottery_id'] = I('post.lottery_id', '', 'trim');
        $data['user_id'] = I('post.user_id', '', 'trim');
        $data['user_name'] = I('post.user_name', '', 'trim');
        $data['type'] = I('post.type', 0, 'intval');
        $data['name'] = I('post.name', '', 'trim');
        $data['page'] = I('post.page', 1, 'intval');
        $data['page_size'] = I('page_size', 10, 'intval');

        $res = $this->model->getLogList($data, true);
        $sheetindex=array(
            'A'=>array('index'=>'A1','name'=>'序号','size'=>'20'),
            'B'=>array('index'=>'B1','name'=>'流水号','size'=>'20'),
            'C'=>array('index'=>'C1','name'=>'活动编号','size'=>'20'),
            'D'=>array('index'=>'D1','name'=>'名称','size'=>'20'),
            'E'=>array('index'=>'E1','name'=>'参与者ID','size'=>'20'),
            'F'=>array('index'=>'F1','name'=>'参与者','size'=>'20'),
            'G'=>array('index'=>'G1','name'=>'获奖情况','size'=>'20'),
            'H'=>array('index'=>'H1','name'=>'获奖金额','size'=>'20'),
            'I'=>array('index'=>'I1','name'=>'参与时间','size'=>'20'),
        );
        $title = '签到日志';
        $type = 15;
        phpExcel($sheetindex,$res['data'],$title,$type);
        exit;
    }
    //导出excel
    public function excelout(){
        // phpExcel();
        //exit;
        /*    $sheetindex=array(
                'A'=>array('index'=>'A1','name'=>'订单编号','size'=>'20'),
                'B'=>array('index'=>'B1','name'=>'故障金额','size'=>'20'),
                'C'=>array('index'=>'C1','name'=>'优惠券','size'=>'20'),
                'D'=>array('index'=>'D1','name'=>'诊断费','size'=>'20'),
                'E'=>array('index'=>'E1','name'=>'小费','size'=>'20'),
                'F'=>array('index'=>'F1','name'=>'订单总金额(元)','size'=>'20'),
                'G'=>array('index'=>'G1','name'=>'支付时间','size'=>'20'),
            );    */
        $sheetindex=array(
            'A'=>array('index'=>'A1','name'=>'序号','size'=>'20'),
            'B'=>array('index'=>'B1','name'=>'年月','size'=>'20'),
            'C'=>array('index'=>'C1','name'=>'维修订单总金额','size'=>'20'),
            'D'=>array('index'=>'D1','name'=>'师傅佣金总金额','size'=>'20'),
            'E'=>array('index'=>'E1','name'=>'师傅奖励总金额','size'=>'20'),
            'F'=>array('index'=>'F1','name'=>'师傅签到总金额','size'=>'20'),
            'G'=>array('index'=>'G1','name'=>'师傅维修金','size'=>'20'),
            'H'=>array('index'=>'H1','name'=>'师傅维修保证金','size'=>'20'),
            'I'=>array('index'=>'I1','name'=>'维修保证金利息总金额','size'=>'20'),
        );
        $title='平台月度营收管理';
        $type=9;
        $redis = S(array('type' => 'redis'));
        $sql=S($this->sqlname);
        $data = M()->query($sql);
        phpExcel($sheetindex,$data,$title,$type);
        exit;

    }

}